﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace Web_Demo
{
    public partial class Login1 : System.Web.UI.Page
    {
        public string pass = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                txt_user.Text = "";
                txt_pass.Text = "";
            }
            if (Request.Cookies["remember"] != null)
            {
                Response.Redirect("index.aspx");
                HttpCookie cookie = Request.Cookies.Get("UserNameAndPassword");
                string cookievalue = cookie.Values["Password"].ToString();
                putsesion(cookievalue);
            }

            //    HttpCookie cookie = Request.Cookies.Get("UserNameAndPassword");
            //    txt_user.Text = cookie.Values["UserName"].ToString();
            //    txt_pass.Text = cookie.Values["Password"].ToString();
            //}

        }
      
        protected void WriteCookie()
        {
            if(chbRemember.Checked==true)
            {
                HttpCookie cookie = new HttpCookie("remember", "yes");
                cookie.Expires = DateTime.Now.AddDays(15);
                Response.Cookies.Add(cookie);
                cookie = new HttpCookie("UserNameAndPassword");
                cookie.Values.Add("UserName", txt_user.Text.Trim());
                cookie.Values.Add("Password", txt_pass.Text.Trim());
                Response.Cookies.Add(cookie);
            }
        }


        protected void btn_Login_Click(object sender, EventArgs e)
        {
            
            WriteCookie();
            DMSdataDataContext dms = new DMSdataDataContext();
            if (dms.DMS_Users.Where(p => p.Name_User == txt_user.Text && p.Pass_User == txt_pass.Text).Count()==1) {
                putsesion(txt_user.Text);
                Response.Redirect("index.aspx");
            }
             else Response.Write("<script>alert('sai roi')</script>");
        
        }
        public void putsesion(string usename) {
            DMSdataDataContext dms = new DMSdataDataContext();
            DMS_User userlogin = dms.DMS_Users.Single(p => p.Name_User == usename);
            HttpContext.Current.Session[constants.user.FIRST_NAME] = userlogin.First_Name;
            HttpContext.Current.Session[constants.user.LAST_NAME] = userlogin.Last_Name;
            HttpContext.Current.Session[constants.user.ID_ROLE_USER] = userlogin.ID_Role_User;
            HttpContext.Current.Session[constants.user.ID_USER] = userlogin.ID_User;
        }

        
    }
}